package chapter11;

import org.junit.Test;

import java.util.*;

/**
 * @author : DuJiabao
 * @Date : 2021/2/19 20:19
 * @Project : thinking-in-java
 * @File : null.java
 * @Desc :
 */
public class MapTest {
  @Test
  public void testHashMap() {
    Random rand = new Random(47);
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < 10000; i++) {
      int r = rand.nextInt(20);
      Integer freq = map.get(r);
      map.put(r, freq == null ? 1 : freq + 1);
    }
    System.out.println(map);
  }

  @Test
  public void containsTest() {
    Map<String, String> map = new HashMap<>();
    map.put("cat", "ketty");
    map.put("dog", "honey");
    System.out.println(map.containsKey("cat")); // 是否包含键， true
    System.out.println(map.containsValue("ketty"));  // 是否包含值， true
    Set<String> strings = map.keySet();
    Collection<String> values = map.values();
    Set<Map.Entry<String, String>> entries = map.entrySet();
    System.out.println(strings);
    System.out.println(values);
    for (Map.Entry<String, String> entry : entries) {
      String key = entry.getKey();
      String value = entry.getValue();
      System.out.println(key + " " + value);
    }
  }

  @Test
  public void ergodicTest() {
    StringBuilder sb = new StringBuilder("{");
    Map<String, String> map = new HashMap<>();
    map.put("cat", "ketty");
    map.put("dog", "honey");
    for (Map.Entry<String, String> entry : map.entrySet()) {
      sb.append(entry.getKey()).append("=").append(entry.getValue()).append(",");  // 它返回自己，使得可以连续append
    }
    sb.delete(sb.length()-1, sb.length());  // 左闭右开
    sb.append("}");
    System.out.println(sb);
  }
}
